using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using octalforty.Waffle.ComponentModel.Navigation;
using octalforty.Waffle.ComponentModel.Security;

namespace octalforty.Waffle.Web.Engine.Web.UI
{
    /// <summary>
    /// Provides a base class for all User Controls in octalforty Waffle Web.
    /// </summary>
    public class UserControl : Spring.Web.UI.UserControl, INavigationServiceDependency, ISecurityServiceDependency
    {
        #region Private Member Variables
        private INavigationService navigationService;
        private ISecurityService securityService;
        #endregion

        /// <summary>
        /// Initializes a new instance of <see cref="UserControl"/> class.
        /// </summary>
        public UserControl()
        {
        }

        #region Overridables
        /// <summary>
        /// First unbinds data from the controls into a data model and
        /// then raises Load event in order to execute all associated handlers.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            InitializePostBackUrls();
        }

        /// <summary>
        /// Initializes postback URLs on controls.
        /// </summary>
        protected virtual void InitializePostBackUrls()
        {
            InitializePostBackUrls(this);
        }
        #endregion

        #region INavigationServiceDependency Members
        /// <summary>
        /// Gets or sets a reference to the <see cref="INavigationService" />.
        /// </summary>
        public INavigationService NavigationService
        {
            get { return navigationService; }
            set { navigationService = value; }
        }
        #endregion

        #region ISecurityServiceDependency Members
        /// <summary>
        /// Gets or sets a reference to the <see cref="ISecurityService" />.
        /// </summary>
        public ISecurityService SecurityService
        {
            get { return securityService; }
            set { securityService = value; }
        }
        #endregion

        private void InitializePostBackUrls(Control control)
        {
            if(control is IButtonControl)
                ((IButtonControl)control).PostBackUrl = Request.RawUrl;

            foreach(Control childControl in control.Controls)
                InitializePostBackUrls(childControl);
        }
    }
}
